<template>
  <div class="add_wrap">
    <!-- 面包屑 -->
    <bread :linktitle="link"> </bread>
    <!-- 面包屑 -->

    <!--添加商品内容 -->
    <!-- 消息提示 开始-->
    <div class="add_box">
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 消息提示 结束-->
      <!-- 步骤条 开始 -->
      <el-steps :active="Number(active)" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 步骤条 结束 -->

      <!-- 标签页 开始-->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <el-tabs
          v-model="active"
          tab-position="left"
          @tab-click="handclick"
          :before-leave="leaveTab"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="ruleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model.number="ruleForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model.number="ruleForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="ruleForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat" required>
              <div style="text-align: left">
                <el-cascader
                  v-model="ruleForm.goods_cat"
                  :options="cate"
                  :props="prop"
                  @change="handleChange"
                ></el-cascader>
              </div>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1" style="text-align: left">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyattrs"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="attr in onlyattrs"
              :key="attr.attr_id"
              :label="attr.attr_name"
            >
              <el-input v-model="attr.attr_vals"> </el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://106.53.73.30:8888/api/private/v1/upload"
              list-type="picture"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="getimage"
              :headers="headerobj"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
              <quill-editor 
              v-model="ruleForm.goods_introduce"
               ref="myQuillEditor" 
              > 

              </quill-editor>
              <el-button type="primary" class="addBtn" @click="add('ruleForm')">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!-- 标签页 结束-->
    </div>
    <!--添加商品内容 -->

    <!-- 上传图片的预览 -->
    <el-dialog
  title="图片预览"
  :visible.sync="dialogVisible"
  width="40%"
  style="text-align:left">
  <span>
    <el-image
      :src="temp"
      fit="contain"></el-image>
  
  </span>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
</el-dialog>
    <!-- 上传图片的预览 -->
  </div>
</template>
<script>
import bread from "../../../common/breadcrumb";
export default {
  name: "add",
  data() {
    var checkprice = (rule, value, callback) => {
      if (!Number.isInteger(value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (value < 0) {
          callback(new Error("不能为负值"));
        } else {
          callback();
        }
      }
    };
    return {
      link: ["商品管理", "添加商品"],
      active: "0", //步骤条索引,
      cate: [], //获取分类数据
      headerobj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      prop: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      }, //制定属性
      ruleForm: {
        goods_name: "", //商品名称
        goods_price: "", //商品价格
        goods_weight: "", //商品重量
        goods_number: "", //商品数量
        goods_cat: [], //商品分类
        attrs: [], //商品的参数属性。
        pics:[],//存放临时路径
        goods_introduce:""//商品介绍

      },
      onlyattrs:[],//商品静态的参数属性
      manyattrs: [], //商品的动态参数属性。
      dialogVisible:false,//图片预览开关
      temp:"",//图片临时路肩
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          {
            required: true,
            message: "请输入商品价格",
            trigger: "blur",
            validator: checkprice,
          },
        ],
        goods_weight: [
          {
            required: true,
            message: "请输入商品重量",
            trigger: "blur",
            validator: checkprice,
          },
        ],
        goods_number: [
          {
            required: true,
            message: "请输入商品数量",
            trigger: "blur",
            validator: checkprice,
          },
        ],
      },
    };
  },
  methods: {
    //监听标签被点击

    leaveTab() {
      if (!this.ruleForm.goods_cat.length) {
        this.$message.error("错误");
        return false;
      } else {
        return true;
      }
    },
    handleChange(value) {
      if (value.length < 3) {
        this.ruleForm.goods_cat = [];
      }
    },
    // 获取分类数据
    async getcate() {
      let mes = await this.$http.get("categories");
      this.cate = mes.data;
    },
    // 监听选项卡点击
    async handclick() {
      if (this.active == "1") {
        let mes = await this.$http.get(
          `categories/${this.ruleForm.goods_cat[2]}/attributes`,
          { params: { sel: "many" } }
        );

        if (mes.meta.status !== 200) return this.$message.error("获取属性失败");
        mes.data.forEach((item, index, arr) => {
          item.attr_vals =
            item.attr_vals.length == "0" ? [] : item.attr_vals.split(",");
        });

        this.manyattrs = mes.data;
      } else if (this.active == "2") {
        let mes = await this.$http.get(
          `categories/${this.ruleForm.goods_cat[2]}/attributes`,
          { params: { sel: "only" } }
        );
        this.onlyattrs = mes.data;
      }
    },
    //文件列表移除文件时的钩子
    handleRemove(file) {
     let tempd = file.response.data.tmp_path
      let ind = this.ruleForm.pics.findIndex(item=>item.pic == tempd)
        this.ruleForm.pics.splice(ind,1)
       
    },
    //点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
        this.temp = file.url
        this.dialogVisible = true
    },
    //文件上传成功时的钩子
    getimage(res){
       let pics = {pic:res.data.tmp_path}
       this.ruleForm.pics.push(pics)
    },

    //添加商品
    add(formName){

        this.$refs[formName].validate(async valid=>{
            if(!valid) return this.$message.error("请填写完整商品信息")
            let from = JSON.parse(JSON.stringify(this.ruleForm))
           from.goods_cat = from.goods_cat.join(",")
    this.manyattrs.forEach(item=>{
        let newinfo = {attr_id:item.attr_id,attr_value:item.attr_vals.join("")}
        from.attrs.push(newinfo)
    })

    this.onlyattrs.forEach(item=>{
        let newinfo = {attr_id:item.attr_id,attr_value:item.attr_vals}
       from.attrs.push(newinfo)
    })
    
     let mes = await this.$http.post('goods',from)
     console.log(from)
    if(mes.meta.status !== 201) return this.$message.error("提交失败")
    this.$message.success("添加商品成功")
    this.$router.push("/home/goods")

        })
    }
  },
  components: {
    bread,
  },
  created() {
    this.getcate();
  },
};
</script>
<style scoped>
.add_box {
  padding: 20px;
  margin-top: 20px;
  background-color: #fff;
}
.el-steps {
  margin: 20px auto;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.add_box {
  text-align: left;
}
.el-upload-list--picture .el-upload-list__item-name {
  cursor: pointer !important;
}
.addBtn{
    margin-top: 15px;
}
</style>